package lab03.test05;

import java.io.*;

public class Test {
    public static void main(String[] args) {
        /**
         *将字符串加密后，通过字符输出流写入文件，然后读取该文件并解密。
         *加密算法为：将原有字符的ASCII码加1，
         *如'A'字符的ASCII码为65，加密后其ASCII码变成66
         *"Hello"加密后的字符串为"Ifmmp"
         */
        String path = "D:\\dev\\lab03\\test05\\test.txt";//保存加密后的字符串

        String str1 = "Hello";//需要加密的字符串
        StringBuffer str2 = new StringBuffer();//保存加密后的字符串

        BufferedWriter writer = null;
        BufferedReader reader = null;

        try {
            writer = new BufferedWriter(new FileWriter(path));
            reader = new BufferedReader(new FileReader(path));

            /*加密处理*/
            for (int i = 0;i<str1.length();i++){
                char ch = (char) (str1.charAt(i)+1);
                str2.append(ch);
            }

            /*加密处理end*/
            writer.write(String.valueOf(str2));
            writer.newLine();//换行
            writer.close();
            System.out.println("加密并写入成功！");
            System.out.println(str1+"加密后为："+str2);

            /*读取文件*/
            String str3 = reader.readLine();
            StringBuffer str4 = new StringBuffer();
            System.out.println("读取成功！！");
            /*解密处理*/
            for (int j = 0; j < str3.length(); j++) {
                str4.append((char)(str3.charAt(j)-1));
            }
            System.out.println(str3+"解密后为:"+str4);

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                writer.close();
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
